﻿using Microsoft.Extensions.DependencyInjection;
using Modules.Cms.Entitys;
using PetaPoco;
using PmSoft;
using PmSoft.ApplicationContext;
using PmSoft.DBContext;
using PmSoft.Repositories;
using PmSoft.Utilities;

namespace Modules.Cms.Repositories;


[UseDI(ServiceLifetime.Scoped)]
public class CmsCustomRepository : Repository<CmsCustom, DefaultDbContext>
{
    public CmsCustomRepository(DefaultDbContext dbContext, IApplicationContext applicationContext) : base(dbContext, applicationContext)
    {
    }

    public IPagedList<CmsCustom> GetCmsCustoms(CmsCustomQuery query, int pageIndex, int pageSize) {
        Sql sql = Sql.Builder;
        sql.Select("id")
            .From("cms_custom")
            .Where("is_deleted=0");
        if (!string.IsNullOrEmpty(query.Keywords))
            sql.Where("(name Like @0 or phone Like @0 or card_no like @0)", "%" + StringUtility.StripSQLInjection(query.Keywords) + "%");
        sql.OrderBy("create_dt DESC");
        var result = GetPagingEntities(pageSize, pageIndex, sql);
        return result;
    }

    internal CmsCustom? GetCustomByKeywords(string keywords)
    {
        if (string.IsNullOrEmpty(keywords)) return null;
        Sql sql = Sql.Builder.Select("id").From("cms_custom").Where("name Like @0 or  phone Like @0 or card_no like @0", "%" + StringUtility.StripSQLInjection(keywords) + "%");
        var id = DbContext.FirstOrDefault<int>(sql);
        if (id == 0)
            return null;
        return Get(id);
    }
}
